package com.isoft.service.impl;

import com.isoft.entity.DfmeFpttEntity;
import com.isoft.mapper.DfmeFpttMapper;
import com.isoft.service.DfmeFpttService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfmeFpttServiceImpl implements DfmeFpttService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeFpttServiceImpl.class);

    @Autowired
    private DfmeFpttMapper dfmeFpttMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    public void parseAndSave(DfmeFpttEntity entity) {
        processFlightData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            DfmeFpttEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeFpttEntity.class);

            if (entity == null || entity.getDflt() == null) {
                throw new IllegalArgumentException("Invalid XML structure");
            }

            // 设置默认机场序号
            if (entity.getDflt().getAirportSeq() == null) {
                entity.getDflt().setAirportSeq(1);
            }

            processFlightData(entity);

            return "Flight planned time data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("XML processing failed", e);
            throw new RuntimeException("Failed to process XML: " + e.getMessage());
        }
    }

    private void processFlightData(DfmeFpttEntity entity) {
        dfmeFpttMapper.insertMeta(entity);
        try {
            dfmeFpttMapper.insertFlightBase(entity);
        } catch (Exception e) {
            if (e.getMessage() != null && e.getMessage().contains("唯一性约束")) {
                logger.warn("Flight base already exists for flight ID: {}, skipping insert.", entity.getDflt().getFlightId());
            } else {
                throw e;
            }
        }
        dfmeFpttMapper.insertFlightRoute(entity);
    }
}